package com.zhida.jiyangcenter.order.fragment

import android.os.Bundle
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import chooongg.base.annotation.ContentLayout
import chooongg.base.loadState.LoadService
import chooongg.base.loadState.LoadUtils
import chooongg.base.loadState.callback.EmptyCallback
import chooongg.base.loadState.callback.ErrorCallback
import chooongg.base.loadState.callback.NetworkCallback
import chooongg.base.utils.*
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.flyco.animation.BounceEnter.BounceTopEnter
import com.flyco.animation.SlideExit.SlideBottomExit
import com.flyco.dialog.listener.OnBtnClickL
import com.flyco.dialog.widget.NormalDialog
import com.google.gson.Gson
import com.zhida.jiyangcenter.DEFAULT_ROW
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.api.*
import com.zhida.jiyangcenter.dialog.ExpressDialog
import com.zhida.jiyangcenter.mian.BaseFragment
import com.zhida.jiyangcenter.order.PayOrderActivity
import com.zhida.jiyangcenter.order.ShopOrderActivity
import com.zhida.jiyangcenter.utils.glideImage
import com.zhida.jiyangcenter.utils.request
import kotlinx.android.synthetic.main.list.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import com.zhida.jiyangcenter.order.CommentOrderActivity as CommentOrderActivity1

@ContentLayout(R.layout.list)
class ShopOrderFragment(val type: Int) : BaseFragment() {
    override fun getTitle(): CharSequence {
        return when (type) {
            -1 -> "全部"
            0 -> "待付款"
            2 -> "待收货"
            5 -> "退款/售后"
            else -> "未知"
        }
    }

    var page = 1
    val adapter = Adapter()
    private lateinit var loadService: LoadService<*>
    override fun initConfig(savedInstanceState: Bundle?) {
        loadService = LoadUtils.getDefault().register(refresh_layout) {
            page = 1
            getData()
        }
        recycler_view.layoutManager = LinearLayoutManager(context)
        recycler_view.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(requireContext())
                .sizeResId(R.dimen.dividerBig).colorResId(R.color.colorBack).build()
        )
        recycler_view.adapter = adapter
        refresh_layout.setOnRefreshListener {
            page = 1
            getData()
        }
        adapter.setOnLoadMoreListener({
            ++page
            getData()
        }, recycler_view)
        adapter.setOnItemClickListener { _, view, position ->
            startActivity<ShopOrderActivity> {
                putExtra("uuid", adapter.data[position].order_uuid)
            }
        }
        adapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.btn_wuliu -> {
                    when (adapter.data[position].state) {
                        "0" -> {
                            val dialog = NormalDialog(context)
                            dialog.content("是否取消订单？")
                                .style(NormalDialog.STYLE_TWO)//
                                .title("温馨提示")
                                .btnNum(2)
                                .btnTextColor(
                                    resColor(R.color.colorAccent),
                                    resColor(R.color.colorAccent)
                                )
                                .btnText("取消", "确认")
                                .titleTextSize(23f)
                                .showAnim(BounceTopEnter())
                                .dismissAnim(SlideBottomExit())
                                .show()

                            dialog.setOnBtnClickL(OnBtnClickL {
                                dialog.dismiss()
                            }, OnBtnClickL {
                                dialog.dismiss()
                                cancel(adapter.data[position].order_uuid ?: "")
                            })
                        }
                        else -> {
                            getExpress(position)
                        }
                    }
                }
                R.id.btn_operate -> {
                    when (adapter.data[position].state) {
                        "0" -> {
                            startActivity<PayOrderActivity> {
                                putExtra("orderCode", adapter.data[position]?.order_uuid)
                                putExtra("total_money", adapter.data[position].actual_payment)
                                putExtra("kind", "0")
                            }
                        }
                        "1" -> {
                            val dialog = NormalDialog(context)
                            dialog.content("您的商品还未发货，是否确认退款？")
                                .style(NormalDialog.STYLE_TWO)//
                                .title("退款")
                                .btnNum(2)
                                .btnTextColor(
                                    resColor(R.color.colorAccent),
                                    resColor(R.color.colorAccent)
                                )
                                .btnText("取消", "确认")
                                .titleTextSize(23f)
                                .showAnim(BounceTopEnter())
                                .dismissAnim(SlideBottomExit())
                                .show()

                            dialog.setOnBtnClickL(OnBtnClickL {
                                dialog.dismiss()
                            }, OnBtnClickL {
                                dialog.dismiss()
                                refundOrder(adapter.data[position].order_uuid ?: "")
                            })
                        }
                        "2" -> {
                            val dialog = NormalDialog(context)
                            dialog.content("请确保您已收到货物，是否确认收货？")
                                .style(NormalDialog.STYLE_TWO)//
                                .title("收货")
                                .btnNum(2)
                                .btnTextColor(
                                    resColor(R.color.colorAccent),
                                    resColor(R.color.colorAccent)
                                )
                                .btnText("取消", "确认")
                                .titleTextSize(23f)
                                .showAnim(BounceTopEnter())
                                .dismissAnim(SlideBottomExit())
                                .show()

                            dialog.setOnBtnClickL(OnBtnClickL {
                                dialog.dismiss()
                            }, OnBtnClickL {
                                dialog.dismiss()
                                receivingOrder(adapter.data[position].order_uuid ?: "")
                            })
                        }
                        "3" -> {
                            startActivity<CommentOrderActivity1>{
                                putExtra("type","1")
                                putExtra("uuid",adapter.data[position].order_uuid)
                            }
                        }
                        "5" -> {

                        }
                        "7" -> {

                        }
                    }
                }
            }
        }
        getData()
    }

    private fun cancel(orderUuid: String) {
        lifecycleScope.request({ APIAccount.service().productOrderCancel(orderUuid) },
            object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                    page = 1
                    getData()
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }
            })
    }

    private fun getExpress(position: Int) {
        lifecycleScope.launch(Dispatchers.IO) {
            val result = KdniaoTrackQueryAPI().getOrderTracesByJson(
                adapter.data[position].logistics_yard,
                adapter.data[position].logistics_code
            )
            val expressEntity = Gson().fromJson(
                result, ExpressEntity::class.java
            )
            if (expressEntity.Traces.isNullOrEmpty()) {
                toast("暂无快递信息")
            } else {
                val dialog = ExpressDialog()
                dialog.arguments = Bundle().apply {
                    putString("img", adapter.data[position].product?.get(0)?.picture)
                    putString("name", adapter.data[position].product?.get(0)?.name)
                    putString("num", adapter.data[position].logistics_code)
                }
                dialog.setExpressEntity(expressEntity.Traces)
                dialog.show(childFragmentManager, "ExpressDialog")
            }
        }
    }

    private fun receivingOrder(orderUuid: String) {
        lifecycleScope.request({ APIAccount.service().productOrderReceiving(orderUuid) },
            object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                    page = 1
                    getData()
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }
            })
    }

    private fun refundOrder(orderUuid: String) {
        lifecycleScope.request({ APIAccount.service().productOrderRefund(orderUuid) },
            object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                    page = 1
                    getData()
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }
            })
    }

    private fun getData() {
        lifecycleScope.request(
            { APIAccount.service().productOrderList(page, type) },
            object : BaseAPI<ProductOrderListEntity>() {
                override fun onSuccess(t: ProductOrderListEntity?, state: Int, msg: String) {
                    if (t != null && !t.orders?.order.isNullOrEmpty()) {
                        if (page <= 1) {
                            adapter.setNewData(t.orders?.order)
                            loadService.showSuccess()
                            refresh_layout.finishRefresh()
                            if (t.orders?.order!!.size < DEFAULT_ROW) {
                                adapter.loadMoreEnd(true)
                            }
                        } else {
                            adapter.addData(t.orders?.order!!)
                            if (t.orders.order.size < DEFAULT_ROW) {
                                adapter.loadMoreEnd(true)
                            } else adapter.loadMoreComplete()
                        }
                    } else onError(APIException(APIException.Type.EMPTY))
                }

                override fun onError(e: APIException) {
                    if (page <= 1) when (e.type) {
                        APIException.Type.EMPTY -> loadService.showCallback(
                            EmptyCallback::class,
                            "暂无商品订单"
                        )
                        APIException.Type.ERROR_NETWORK -> loadService.showCallback(NetworkCallback::class)
//                        APIException.Type.NOT_LOGIN -> loadService.showCallback(NotLoginCallback::class)
                        else -> loadService.showCallback(ErrorCallback::class, e.eMessage)
                    } else when (e.type) {
                        APIException.Type.EMPTY -> {
                            adapter.loadMoreFail()
                        }
                        else -> adapter.loadMoreFail()
                    }
                }

            })
    }

    class Adapter :
        BaseQuickAdapter<ProductOrderListEntity.Orders.Order, BaseViewHolder>(R.layout.item_shop_order) {
        override fun convert(helper: BaseViewHolder, item: ProductOrderListEntity.Orders.Order?) {
            val rv_buy_car = helper.getView<RecyclerView>(R.id.rv_buy_car)
            rv_buy_car.layoutManager = object : LinearLayoutManager(mContext) {
                override fun canScrollVertically(): Boolean {
                    return false
                }
            }
            rv_buy_car.addItemDecoration(
                HorizontalDividerItemDecoration.Builder(mContext).sizeResId(R.dimen.dividerSmall)
                    .colorResId(R.color.white).build()
            )
            rv_buy_car.adapter = ItemAdapter().apply {
                setNewData(item?.product)
            }
            when (item?.state) {
                "0" -> {
                    helper.setGone(R.id.btn_wuliu, true).setGone(R.id.btn_operate, true)
                        .setText(R.id.btn_wuliu, "取消订单")
                        .setText(R.id.btn_operate, "去支付").setText(R.id.tv_order_type, "待支付")
                }
                "1" -> {
                    helper.setGone(R.id.btn_wuliu, false).setGone(R.id.btn_operate, true)
                        .setText(R.id.btn_operate, " 退 款 ").setText(R.id.tv_order_type, "待发货")
                }
                "2" -> {
                    helper.setGone(R.id.btn_wuliu, true).setGone(R.id.btn_operate, true)
                        .setText(R.id.btn_operate, "确认收货").setText(R.id.btn_wuliu, "查看物流")
                        .setText(R.id.tv_order_type, "待收货")
                }
                "3" -> {
                    helper.setGone(R.id.btn_wuliu, false).setGone(R.id.btn_operate, true)
                        .setText(R.id.btn_operate, "去评价").setText(R.id.btn_wuliu, "查看物流")
                        .setText(R.id.tv_order_type, "待评价")
                }
                "4" -> {
                    helper.setGone(R.id.btn_wuliu, true).setGone(R.id.btn_operate, false)
                        .setText(R.id.btn_wuliu, "查看物流")
                        .setText(R.id.tv_order_type, "已完成")
                }
                "5" -> {
                    helper.setGone(R.id.btn_wuliu, false).setGone(R.id.btn_operate, false)
                        .setText(R.id.btn_operate, "退款进度").setText(R.id.tv_order_type, "待退款")
                }
                "6" -> {
                    helper.setGone(R.id.btn_wuliu, false).setGone(R.id.btn_operate, false)
                        .setText(R.id.tv_order_type, "已退款")
                }
                "7" -> {
                    helper.setGone(R.id.btn_wuliu, false).setGone(R.id.btn_operate, false)
                        .setText(R.id.btn_operate, "退货进度").setText(R.id.tv_order_type, "待退货")
                }
                "8" -> {
                    helper.setGone(R.id.btn_wuliu, false).setGone(R.id.btn_operate, false)
                        .setText(R.id.tv_order_type, "已退货")
                }
                "9" -> {
                    helper.setGone(R.id.btn_wuliu, false).setGone(R.id.btn_operate, false)
                        .setText(R.id.tv_order_type, "已取消")
                }

            }
            helper.setText(
                R.id.tv_shop_order_money,
                "共${item?.num_total}件商品 合计：¥${item?.actual_payment}"
            )
                .addOnClickListener(R.id.btn_operate).addOnClickListener(R.id.btn_wuliu)
        }

        class ItemAdapter :
            BaseQuickAdapter<ProductOrderListEntity.Orders.Order.Product, BaseViewHolder>(R.layout.item_item_shop_order) {
            override fun convert(
                helper: BaseViewHolder,
                item: ProductOrderListEntity.Orders.Order.Product?
            ) {
                glideImage(helper.getView(R.id.niv_item_buy_car), item?.picture ?: "")
                helper.setText(R.id.tv_item_buy_car_name, item?.name)
                    .setText(R.id.tv_item_buy_car_money, "￥${item?.price}")
                    .setText(R.id.tv_item_num, "x${item?.num}")
            }

        }

    }
}